package com.wjk.kylin.modules.system.dept.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjk.kylin.modules.system.dept.entity.Dept;
import com.wjk.kylin.modules.system.dept.mapper.DeptMapper;
import com.wjk.kylin.modules.system.dept.service.IDeptService;
import com.wjk.kylin.modules.system.role.service.IRoleDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  部门表 服务实现类
 * </p>
 *
 * @author wangjkui
 * @since 2020/5/22
 */
@Service
@Transactional(readOnly=true)
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {
    @Autowired
    private IRoleDeptService roleDeptService;

    @Override
    @Transactional(readOnly=false)
    public boolean save(Dept dept) {
        dept.preInsert();

        return super.save(dept);
    }

    @Override
    @Transactional(readOnly=false)
    public boolean update(Dept dept) {
        dept.preUpdate();

        return super.updateById(dept);
    }

    @Override
    @Transactional(readOnly=false)
    public boolean deleteById(String deptId) {

        //1.删除角色岗位关联数据
        roleDeptService.deleteByDeptIds(Arrays.asList(deptId));

        return super.removeById(deptId);
    }

    @Override
    public boolean hasChildByDeptId(String deptId) {
        QueryWrapper<Dept> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", deptId);
        int count = this.count(wrapper);
        if(count > 0){
            return true;
        }
        return false;
    }

    @Override
    public List<Dept> treeList() {
        return listWithTree(super.list(),"0");
    }

    /**
     * 组装tree
     * @param all
     * @param parentId
     * @return
     */
    private List<Dept> listWithTree(List<Dept> all, String parentId) {
        List<Dept> rootList = all.stream().filter(dept ->
                dept.getParentId().equals(parentId)
        ).map(dept->{
            dept.setChildren(listWithTree(all,dept.getId()));
            return dept;
        }).sorted(Comparator.comparing(Dept::getSort))
                .collect(Collectors.toList());
        return rootList;
    }

    /**
     * 获取当前节点的所有子节点id
     * @param all 部门集合
     * @param deptIds 所有子节点id
     * @param parentId 当前节点 id
     */
    @Override
    public void listWithId(List<Dept> all,List<String> deptIds, String parentId) {
        for (Dept dept:all){
            if(dept.getParentId().equals(parentId)){
                deptIds.add(dept.getId());
                listWithId(all,deptIds,dept.getId());
            }
        }
    }

}
